package org.xlp.base.application.util;

import org.xlp.utils.XLPStringUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * Description: http请求工具类
 * <br/>date: 2024/12/10 23:29
 *
 * @version 1.0
 * @author: xlp
 */
public class RequestUtils {
    /**
     * 获取请求客户端ip地址
     * @param request
     * @return
     */
    public static String getClientIP(HttpServletRequest request){
        String xfHeader = request.getHeader("X-Forwarded-For");
        if (XLPStringUtil.isEmpty(xfHeader)) {
            xfHeader = request.getHeader("Proxy-Client-IP");
        }
        if (XLPStringUtil.isEmpty(xfHeader)) {
            xfHeader = request.getHeader("WL-Proxy-Client-IP");
        }
        if (XLPStringUtil.isEmpty(xfHeader)) {
            xfHeader = request.getHeader("HTTP_CLIENT_IP");
        }
        if (XLPStringUtil.isEmpty(xfHeader)) {
            xfHeader = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (XLPStringUtil.isEmpty(xfHeader)) {
            xfHeader = request.getRemoteAddr();
        }

        // 如果 xfHeader 包含多个IP地址（例如通过多个代理），则取第一个
        if (xfHeader != null && xfHeader.contains(",")) {
            xfHeader = xfHeader.split(",")[0];
        }

        return xfHeader;
    }

    /**
     * 获取请求客户端ip地址
     * @param request
     * @return
     */
    public static String getClientAllIP(HttpServletRequest request){
        String xfHeader = request.getHeader("X-Forwarded-For");
        String resultIp = "";
        if (!XLPStringUtil.isEmpty(xfHeader)) {
            resultIp += "X-Forwarded-For:" + xfHeader + ";";
        }

        xfHeader = request.getHeader("Proxy-Client-IP");
        if (!XLPStringUtil.isEmpty(xfHeader)) {
            resultIp += "Proxy-Client-IP:" + xfHeader + ";";
        }

        xfHeader = request.getHeader("WL-Proxy-Client-IP");
        if (!XLPStringUtil.isEmpty(xfHeader)) {
            resultIp += "WL-Proxy-Client-IP:" + xfHeader + ";";
        }

        xfHeader = request.getHeader("HTTP_CLIENT_IP");
        if (!XLPStringUtil.isEmpty(xfHeader)) {
            resultIp += "HTTP_CLIENT_IP:" + xfHeader + ";";
        }

        xfHeader = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (!XLPStringUtil.isEmpty(xfHeader)) {
            resultIp += "HTTP_X_FORWARDED_FOR:" + xfHeader + ";";
        }

        xfHeader = request.getRemoteAddr();
        if (!XLPStringUtil.isEmpty(xfHeader)) {
            resultIp += "request.getRemoteAddr():" + xfHeader + ";";
        }

        return resultIp;
    }

    /**
     * 获取浏览器信息
     * @param request
     * @return
     */
    public static String getBrowserInfo(HttpServletRequest request){
        String s = XLPStringUtil.emptyTrim(request.getHeader("User-Agent"));
        if (s.length() > 500) {
            return s.substring(0, 500);
        }
        return s;
    }
}
